package com.tcs.test.executor.test;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tcs.test.executor.base.BeseExecutorRun;


/**
 * 奇数偶数打印
 * @author wangBo
 */
public class JiOuPrint extends BeseExecutorRun {
	
	private final Logger logger = LoggerFactory.getLogger(JiOuPrint.class);
	
	private int count = 100;
	
	ReentrantLock lock = new ReentrantLock();
	
	Condition condition = lock.newCondition();

	@Override
	protected void service() {
		JiShu jishu = new JiShu();
		OuShu oushu = new OuShu();
		new Thread(oushu , "out").start();
		new Thread(jishu , "ji").start();
	}
	
	@Test
	public void test1() {
		try {
			super.go();
		} catch (InterruptedException e) {
			logger.error("" , e);
		}
	}
	
	public class JiShu implements Runnable {

		@Override
		public void run() {
			lock.lock();
			try {
				while (count > 0) {
					if (count % 2 == 1) {
						logger.info("count : {} " , count);
						count--;
						condition.signal();
					} else {
						try {
							condition.await();
						} catch (InterruptedException e) {
							logger.error("" , e);
						}
					}
				}
			} finally {
				lock.unlock();
			}
		}
	}
	
	public class OuShu implements Runnable {

		@Override
		public void run() {
			lock.lock();
			try {
				while (count > 0) {
					if (count % 2 == 0) {
						logger.info("count : {} " , count);
						count--;
						condition.signal();
					} else {
						try {
							condition.await();
						} catch (InterruptedException e) {
							logger.error("" , e);
						}
					}
				}
			} finally {
				lock.unlock();
			}
		}
	}
}